package com.css.zfzx.sjcj.modules.qhmapfiles.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.utils.*;
import com.css.zfzx.sjcj.common.utils.BeanUtil;
import com.css.zfzx.sjcj.common.utils.CheckObjFields;
import com.css.zfzx.sjcj.common.utils.VectorDataUtil;
import com.css.zfzx.sjcj.modules.qhmapfiles.repository.QhMapFilesImport;
import com.css.zfzx.sjcj.modules.qhmapfiles.repository.QhMapFilesNativeRepository;
import com.css.zfzx.sjcj.modules.qhmapfiles.repository.QhMapFilesRepository;
import com.css.zfzx.sjcj.modules.qhmapfiles.repository.entity.QhMapFilesEntity;
import com.css.zfzx.sjcj.modules.qhmapfiles.service.QhMapFilesService;
import com.css.zfzx.sjcj.modules.qhmapfiles.viewobjects.QhMapFilesQueryParams;
import com.css.zfzx.sjcj.modules.qhrisklevelmappoint.service.QhRiskLevelMapPointService;
import com.css.zfzx.sjcj.modules.qhrisklevelmappointprovince.service.QhRiskLevelMapPointProvinceService;
import com.css.zfzx.sjcj.modules.qhrisklevelmappolygon.service.QhRiskLevelMapPolygonService;
import com.css.zfzx.sjcj.modules.qhrisklevelmappolygonprovince.service.QhRiskLevelMapPolygonProvinceService;
import com.css.zfzx.sjcj.modules.qhriskvisualshow.service.QhProbabilityEarthquakeDangerService;
import com.css.zfzx.sjcj.modules.qhriskvisualshowprovince.service.QhProbabilityEarthquakeDangerProvinceService;
import com.css.zfzx.sjcj.modules.qhsiteclassresult.service.QhSiteClassResultService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @author zyt
 * @date 2022-04-19
 */
@Service
public class QhMapFilesServiceImpl implements QhMapFilesService {

    private static final Logger log = LoggerFactory.getLogger(QhMapFilesServiceImpl.class);

	@Autowired
    private QhMapFilesRepository qhMapFilesRepository;
    @Autowired
    private QhMapFilesNativeRepository qhMapFilesNativeRepository;
    @Autowired
    private QhMapFilesImport qhMapFilesInitial;
    @Autowired
    private QhProbabilityEarthquakeDangerService qhProbabilityEarthquakeDangerService;
    @Autowired
    private QhProbabilityEarthquakeDangerProvinceService qhProbabilityEarthquakeDangerProvinceService;
    @Autowired
    private QhRiskLevelMapPointService qhRiskLevelMapPointService;
    @Autowired
    private QhRiskLevelMapPointProvinceService qhRiskLevelMapPointProvinceService;
    @Autowired
    private QhRiskLevelMapPolygonService qhRiskLevelMapPolygonService;
    @Autowired
    private QhRiskLevelMapPolygonProvinceService qhRiskLevelMapPolygonProvinceService;
    @Autowired
    private QhSiteClassResultService qhSiteClassResultService;

    @Override
    public QhMapFilesEntity getQhMapFilesById(String id) {
        QhMapFilesEntity qhMapFiles = this.qhMapFilesRepository.findById(id).orElse(null);
         return qhMapFiles;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public QhMapFilesEntity saveQhMapFiles(QhMapFilesEntity qhMapFiles) {
        String uuid = UUIDGenerator.getUUID();
        qhMapFiles.setUuid(uuid);
        qhMapFiles.setCreateUser(PlatformSessionUtils.getUserId());
        qhMapFiles.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        this.qhMapFilesRepository.save(qhMapFiles);
        return qhMapFiles;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public QhMapFilesEntity updateQhMapFiles(QhMapFilesEntity qhMapFiles) {
        qhMapFiles.setUpdateUser(PlatformSessionUtils.getUserId());
        qhMapFiles.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        String id = qhMapFiles.getUuid();
        QhMapFilesEntity one = qhMapFilesRepository.findById(id).get();
        BeanUtil.copyPropertiesIgnoreNull(qhMapFiles, one);
        this.qhMapFilesRepository.save(one);
        return qhMapFiles;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteQhMapFiles(List<String> ids) {
        List<QhMapFilesEntity> qhMapFilesList = this.qhMapFilesRepository.findAllById(ids);
        if(!PlatformObjectUtils.isEmpty(qhMapFilesList) && qhMapFilesList.size() > 0) {
            for(QhMapFilesEntity qhMapFiles : qhMapFilesList) {
                this.qhMapFilesRepository.delete(qhMapFiles);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteQhMapFilesByFileName(List<String> fileNames, String province) throws Exception {
        int idx = -1;
        for (int i = 0; i < fileNames.size(); i++) {
            QhMapFilesQueryParams queryParams = new QhMapFilesQueryParams();
            queryParams.setProvince(province);
            queryParams.setAffiliatedFileName(fileNames.get(i));
            List<QhMapFilesEntity> qhPEDList = this.qhMapFilesNativeRepository.searchMapFilesByJDBC(queryParams);
            if(!PlatformObjectUtils.isEmpty(qhPEDList) && qhPEDList.size() > 0) {
                /*for(QhMapFilesEntity qhSiteClassResult : qhSiteClassResultList) {
                    this.qhSiteClassResultRepository.delete(qhSiteClassResult);
                }*/
                //物理删
                //qhMapFilesInitial.sqlBatchDeleteEntities(qhPEDList);
                //逻辑删
                idx = qhMapFilesInitial.sqlBatchLogicDeleteEntities(qhPEDList);
            }
        }
        return idx;
    }

    //根据参数删除文件
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteQhMapFilesByParams(QhMapFilesQueryParams queryParams) throws Exception {
        int idx = -1;
        List<QhMapFilesEntity> qhPEDList = this.qhMapFilesNativeRepository.searchMapFilesByJDBC(queryParams);
        if(!PlatformObjectUtils.isEmpty(qhPEDList) && qhPEDList.size() > 0) {
            //物理删
            //qhMapFilesInitial.sqlBatchDeleteEntities(qhPEDList);
            //逻辑删
            idx = qhMapFilesInitial.sqlBatchLogicDeleteEntities(qhPEDList);
        }
        return idx;
    }

    @Override
    public JSONObject getQhMapFiles(QhMapFilesQueryParams queryParams) {
        List<QhMapFilesEntity> qhPEDEntities = this.qhMapFilesNativeRepository.searchMapFilesByJDBC(queryParams);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("data", qhPEDEntities);
        return jsonObject;
    }

    @Override
    public JSONObject searchQhMapFiles(QhMapFilesQueryParams queryParams) {
        //List<QhMapFilesEntity> qhPEDEntities = this.qhMapFilesNativeRepository.searchMapFiles(queryParams);
        List<QhMapFilesEntity> qhPEDEntities = this.qhMapFilesNativeRepository.searchMapFilesByJDBC(queryParams);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("data", qhPEDEntities);
        return jsonObject;
    }

    //根据参数查询文件
    @Override
    public List<QhMapFilesEntity> searchQhMapFilesByParams(QhMapFilesQueryParams queryParams) {
        List<QhMapFilesEntity> list = this.qhMapFilesNativeRepository.searchMapFilesByJDBC(queryParams);

        return list;
    }

    //查询所有未保存的文件
    @Override
    public List<QhMapFilesEntity> searchAllUnsaveQhMapFiles() {
        List<QhMapFilesEntity> list = this.qhMapFilesNativeRepository.searchAllUnsaveMapFilesByJDBC();

        return list;
    }

    //查询上传未保存文件数量
    @Override
    public int lookUpMapFiles(String saveType, String type, String qualityStatus, String province, String city, String area) {
        int count = 0;
        //根据类型查询未保存的文件
        QhMapFilesQueryParams queryParams = new QhMapFilesQueryParams();
        queryParams.setType(type);//上传类型（PED_,RLM_,RLMPolygon_,SCR_）
        queryParams.setIsDelete("0");//未删除
        queryParams.setIsSave(saveType);//保存状态：0未保存1已保存2正在保存
        queryParams.setQualityStatus(qualityStatus);//上传省市级类型（0：省，1：市）
        queryParams.setProvince(province);
        queryParams.setCity(city);
        queryParams.setArea(area);
        List<QhMapFilesEntity> list = searchQhMapFilesByParams(queryParams);
        if(list!=null && list.size()>0){
            count = list.size();
        }

        return count;
    }

    //批量更新为已删除状态
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateLogicDeleteQhMapFiles(List<QhMapFilesEntity> list) throws Exception {
        int count = this.qhMapFilesInitial.sqlBatchLogicDeleteEntities(list);

        return count;
    }

    //批量更新为已保存状态
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateSaveQhMapFiles(List<QhMapFilesEntity> list) throws Exception {
        int count = this.qhMapFilesInitial.sqlBatchUpdateEntities(list);

        return count;
    }

    //更新为已保存状态
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateSaveQhMapFile(QhMapFilesEntity qhMapFilesEntity) throws Exception {
        List<QhMapFilesEntity> list = new ArrayList<QhMapFilesEntity>();
        list.add(qhMapFilesEntity);
        int count = this.qhMapFilesInitial.sqlBatchUpdateEntities(list);

        return count;
    }

    //更新为正在保存状态
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateSaveNowQhMapFile(QhMapFilesEntity qhMapFilesEntity) throws Exception {
        List<QhMapFilesEntity> list = new ArrayList<QhMapFilesEntity>();
        list.add(qhMapFilesEntity);
        int count = this.qhMapFilesInitial.sqlBatchUpdateNowEntities(list);

        return count;
    }

    //根据类型保存到数据库不同表
    @Override
    public String saveQhMapFilesToDatabaseByType(QhMapFilesEntity qhMapFilesEntity) {
        String type = qhMapFilesEntity.getType();
        String filePath = qhMapFilesEntity.getFilepath();
        String affiliatedFileName = qhMapFilesEntity.getAffiliatedFileName();
        String province = qhMapFilesEntity.getProvince();
        String city = qhMapFilesEntity.getCity();
        String area = qhMapFilesEntity.getArea();
        String createUser  = qhMapFilesEntity.getCreateUser();
        String postfix = qhMapFilesEntity.getPostfix();//文件类型：shp | gdb
        String codeType = qhMapFilesEntity.getCodeType();//编码类型（0：UTF-8，1：GBK）
        int dataLength = qhMapFilesEntity.getDataLength();
        if(codeType.equals("0")){
            codeType = "UTF-8";
        }else{
            codeType = "GBK";
        }
        System.out.println(new Date()+"------开始导入."+affiliatedFileName+"----数据长度."+dataLength);
        //test
        /*if(dataLength>1000000){
            return "导入失败."+affiliatedFileName+"数据长度过大"+dataLength;
        }*/
        String resMsg = affiliatedFileName;//返回结果
        String result = "";
        try{
            //更新为正在保存状态
            this.updateSaveNowQhMapFile(qhMapFilesEntity);
            //保存
            if(postfix.equals("shp")){//保存shp文件
                if(type.equals("PED_")){//PGA
                    if(!("".equals(city))){//PGA
                        result = this.qhProbabilityEarthquakeDangerService.newImportShapeFile(filePath,province,city,area,createUser,codeType,dataLength);
                    }else{//PGA(省)
                        result = this.qhProbabilityEarthquakeDangerProvinceService.newImportShapeFile(filePath,province,city,area,createUser,codeType,dataLength);
                    }
                }else if(type.equals("RLM_")){//等级点
                    if(!("".equals(city))){//等级点
                        result = this.qhRiskLevelMapPointService.newImportShapeFile(filePath,province,city,area,createUser,codeType,dataLength);
                    }else{//等级点(省)
                        result = this.qhRiskLevelMapPointProvinceService.newImportShapeFile(filePath,province,city,area,createUser,codeType,dataLength);
                    }
                }else if(type.equals("RLMPolygon_")){//等级面
                    if(!("".equals(city))){//等级面
                        result = this.qhRiskLevelMapPolygonService.newImportShapeFile(filePath,province,city,area,createUser,codeType,dataLength);
                    }else{//等级面(省)
                        result = this.qhRiskLevelMapPolygonProvinceService.newImportShapeFile(filePath,province,city,area,createUser,codeType,dataLength);
                    }
                }else if(type.equals("SCR_")){//SiteClass
                    result = this.qhSiteClassResultService.newImportShapeFile(filePath,province,city,area,createUser,codeType,dataLength);
                }
            }else if(postfix.equals("gdb")){//保存GDB文件
                if(type.equals("PED_")){//PGA
                    if(!("".equals(city))){//PGA
                        result = this.qhProbabilityEarthquakeDangerService.newImportGDBFile(filePath,province,city,area,createUser,codeType,dataLength);
                    }else{//PGA(省)
                        result = this.qhProbabilityEarthquakeDangerProvinceService.newImportGDBFile(filePath,province,city,area,createUser,codeType,dataLength);
                    }
                }else if(type.equals("RLM_")){//等级点
                    if(!("".equals(city))){//等级点
                        result = this.qhRiskLevelMapPointService.newImportGDBFile(filePath,province,city,area,createUser,codeType,dataLength);
                    }else{//等级点(省)
                        result = this.qhRiskLevelMapPointProvinceService.newImportGDBFile(filePath,province,city,area,createUser,codeType,dataLength);
                    }
                }else if(type.equals("RLMPolygon_")){//等级面
                    if(!("".equals(city))){//等级面
                        result = this.qhRiskLevelMapPolygonService.newImportGDBFile(filePath,province,city,area,createUser,codeType,dataLength);
                    }else{//等级面(省)
                        result = this.qhRiskLevelMapPolygonProvinceService.newImportGDBFile(filePath,province,city,area,createUser,codeType,dataLength);
                    }
                }
            }
            //已保存成功
            if(result.contains("成功导入")){
                //根据类型查询未保存的文件
                QhMapFilesQueryParams queryParams = new QhMapFilesQueryParams();
                queryParams.setType(type);//上传类型（PED_,RLM_,RLMPolygon_,SCR_）
                queryParams.setIsDelete("0");//未删除
                queryParams.setIsSave("0");//未保存
                queryParams.setProvince(province);
                queryParams.setCity(city);
                queryParams.setArea(area);
                List<QhMapFilesEntity> list = searchQhMapFilesByParams(queryParams);
                if(list!=null && list.size()>0){
                    //批量更新为已保存状态
                    //this.updateSaveQhMapFiles(list);
                    //批量更新为已删除状态
                    this.updateLogicDeleteQhMapFiles(list);
                }
                //更新为已保存状态
                this.updateSaveQhMapFile(qhMapFilesEntity);
                resMsg += "导入成功." + result;
            }else{
                resMsg += "导入失败." + result;
            }
        }catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        return resMsg;
    }
}
